function RiskEvaluateChart() {
	var data;
	var type = [];
	var yData = [];
    
	var map = new Map();
	// 五个等级颜色，五级最高（红色，橙色，黄色，蓝色，绿色）
	var color = [ '#71C671', '#4876FF', '#EEB422', '#FF6347', '#FF0000' ];
	// 设备个数和等级关系,最低级别为1个，2级为2个，3级为3或4个，4级为5或6个，5级为7以上（在评估指标中定义）
	var grade = [ 1, 2, 4, 6 ];
	var tb = null;
	var treeMapChart = new treeMap('treeMapChart');
	var barChart = new CategoryBar('barChart');
	var stationId = $("#stationId").val();
	var stationName=decodeURIComponent($("#stationName").val());
	console.log(stationName);
	var evalType;//评估类型
	$("#changeViewBtn").click(function() {
		if ($("#barChart").hasClass("isHidden")) {
			$("#barChart").removeClass("isHidden");
			$("#treeMapChart").addClass("isHidden");
			barChart.getChart().resize();
		} else {
			$("#treeMapChart").removeClass("isHidden");
			$("#barChart").addClass("isHidden");
			treeMapChart.getChart().resize();
		}
	});
	$(".box-header").on("click", "#backBtn", function() {
		$(".box-header").hide();
		$(".chartDiv").show();
		$(".detailDiv").hide();
		$(".box-header").empty();
		$("#conclusion").show();
	});
	var breakExpParam;//断路器异常参数
	this.initPrimeData = function() {
		// 根据站id获取所有类型的风险设备信息（rest获取）
		$.getJSON("/rest/primerisk/getPrimeRiskProject4PieChart/" + stationId, function(
				result) {
			breakExpParam=result.breakExpParam;
			initMainPie(result);
		});
		// 矩形图数据,value为权重（在指标中定义），映射到矩形面积，itemStyle映射到等级
		/*data = [ {
			name : "反措未执行",
			value : [ 10 ]
		}, {
			name : "未处理缺陷",
			value : [ 10 ]
		}, {
			name : "超期服役",
			value : [ 15 ]
		}, {
			name : "超期未检",
			value : [ 15 ]
		}, {
			name : "断路器动作异常",
			value : [ 25 ]
		}, {
			name : "CT饱和",
			value : [ 25 ]
		}
		
		 * , { name : "变压器暂态过载", value : [ 5 ] }
		 
		];*/
		//getBarGrade();
		//getTreeMapGrade();
		//initBarChart();
		//initTreeMapChart();
	}
	this.initSecondData = function() {
		// 根据站id获取所有类型的风险设备信息（rest获取）
		$.getJSON("/rest/SecRiskEvaluateService/getSecRiskProject4PieChart/" + stationId, function(
				result) {
			initMainPie(result);
		});
		// 矩形图数据,value为权重（在指标中定义），映射到矩形面积，itemStyle映射到等级
		/*data = [ {
			name : "反措未执行",
			value : [ 10 ]
		}, {
			name : "未处理缺陷",
			value : [ 10 ]
		}, {
			name : "超期未检",
			value : [ 20 ]
		}, {
			name : "超期服役",
			value : [ 20 ]
		}, {
			name : "通信中断",
			value : [ 15 ]
		}, {
			name : "保护装置异常",
			value : [ 20 ]
		}, {
			name : "保护响应异常",
			value : [ 5 ]
		} ];*/
		/*getBarGrade();
		getTreeMapGrade();
		initBarChart();
		initTreeMapChart();*/
	}
	//画左边双层饼图
	function initMainPie(dataSet){	
		initDescDiv(dataSet);//描述
		$("#conclusion").html(stationName+dataSet.conclusion);
		var mainPie= echarts.init(document.getElementById('mainPie'));
		option = {
			    tooltip: {
			        trigger: 'item',
			        formatter: "{a} <br/>{b}: {c} ({d}%)"
			    },
			    grid:{
			    	top:20,
			    	left:10
			    },
			    series: [
			        {
			            name:'风险等级',
			            type:'pie',
			            selectedMode: 'single',
			            radius: [0, '55%'],
			            label: {
			                normal: {
			                    position: 'inner'
			                }
			            },
			            labelLine: {
			                normal: {
			                    show: false
			                }
			            },
			            data:dataSet.pieMain
			        },
			        {
			            name:'评估类型',
			            type:'pie',
			            radius: ['70%', '85%'],
			            label:{
			            	normal:{formatter: "{b}: {c} ({d}%)"}
			            },
			            data:dataSet.pieSub
			        }
			    ]
			};
		mainPie.setOption(option);
		mainPie.on('click', function (params) {
			evalType=params.name;
			initDetailPie(dataSet.subDatas,dataSet.counts);
		});
		for(var type in dataSet.subDatas){
			if(Object.keys(dataSet.subDatas[type]).length>0){
				evalType=type;
				initDetailPie(dataSet.subDatas,dataSet.counts);
				break;
			}
		}
	}
	//右边风险评估模型说明
	function initDescDiv(dataSet){
		var data=dataSet.desc;
		var ul=$("<ul></ul>").appendTo($("#descDiv"));
		for(var name in data){
			var mainli=$("<li class='riskLevel'></li>").html(name).appendTo(ul);
			for(var type in data[name]){
				var li=$("<li class='riskFactor'></li>").html(type+":<span style='font-size:24px;color:red'>"+data[name][type]+"</span>").appendTo(ul);
			}
		}
	}
	//sub饼图(两个饼图，左边是该类型占该类型总数比例，右边是异常发生次数（超期服役，超期未检例外，记录数就是设备数）)
	function initDetailPie(subDatas,counts){
		var pie1 = new Pie("subPie1");
		var pie1Data=[[evalType,Object.keys(subDatas[evalType]).length]];
		switch (evalType){
			case "超期未检":
			case "超期服役":
			case "反措未执行":
			case "未处理缺陷":
			case "保护响应异常":
			case "通信中断":
			case "保护装置异常":
				pie1Data.push(["正常",counts["total"]-Object.keys(subDatas[evalType]).length]);
				break;
			case "断路器动作异常":
				pie1Data.push(["正常",counts["断路器"]-Object.keys(subDatas[evalType]).length]);
				break;
			case "CT饱和":
				pie1Data.push(["正常",counts["CT"]-Object.keys(subDatas[evalType]).length]);
				break;
			case "变压器暂态过载":
				pie1Data.push(["正常",counts["变压器"]-Object.keys(subDatas[evalType]).length]);
				break;
		}
		pie1.setPie(pie1Data);
		pie1.setPieOuterRadius("50%");
		pie1.setColors( ["#dd4b39","#00a65a"]);
		var option = pie1.getOption();
		option.title.text = evalType+"设备数目占比";
		option.legend.top=40;
		option.legend.orient='vertical';
		option.legend.x='left';
		option.grid.left='left';
		option.tooltip.formatter= "{b}: {c} ({d}%)";
		option.series[0].label.normal.formatter="{b}: {c} ({d}%)";
		pie1.show();
		
		//右边饼图
		var pie2 = new Pie("subPie2");
		var pie2Data=[];
		for(var name in subDatas[evalType]){
			pie2Data.push([name,subDatas[evalType][name].length]);
		}
		pie2.setPie(pie2Data);
		pie2.setPieOuterRadius("50%");
		var option = pie2.getOption();
		option.title.text = "各设备发生异常次数分布";
		option.legend.top=40;
		option.legend.orient='vertical';
		option.legend.x='left';
		option.grid.left='left';
		option.legend.show=true;
		option.tooltip.formatter= "{b}: {c} ({d}%)";
		option.series[0].label.normal.formatter="{b}: {c} ({d}%)";
		pie2.show();
		if(evalType!="保护装置异常"){
			pie2.getChart().on("click",function(params){
				$(".box-header").show();
				$("#conclusion").hide();
				if(tb){
					tb.getTable().destroy();
					$("#detailTb").empty();
				}
				$("#chartDiv").hide();
				$("#detailDiv").show();
				var name=params.name+evalType.replace("保护","");
				$("#tbTitle span").html(name);
				initTbData(subDatas[evalType][params.name]);
			});
		}
	}
	

	function getLocalTime(nS) {
		return new Date(nS).toLocaleString();
	}

	function initTbData(value) {
		var info = [];
		switch (evalType) {
		case "反措未执行":
			// 反措未执行
			for ( var i in value) {
				info.push([ value[i].deviceName, value[i].content,
						value[i].responsibleDepartment,
						getLocalTime(value[i].planStartDate.time),
						getLocalTime(value[i].planFinishDate.time) ]);
			}
			var columns = [ "设备名称", "反措内容", "责任单位", "计划时间", "计划结束时间" ];
			initTb(columns, info);
			break;
		case "缺陷":
			// 缺陷
			for ( var i in value) {
				info.push([ value[i].deviceName, value[i].defectDesc,
						value[i].manufacturer, value[i].deviceType ]);
			}
			var columns = [ "设备名称", "缺陷类型", "生产厂家", "设备类型" ];
			initTb(columns, info);
			break;
		case "超期服役":
			// 超期服役
			for ( var i in value) {
				info.push([ value[i].name, getLocalTime(value[i].runDate.time),
						value[i].runLimit + "天", value[i].manufacturer,
						value[i].voltage ]);
			}
			var columns = [ "设备名称", "投运日期", "运行年限", "生产厂家", "电压等级" ];
			initTb(columns, info);
			break;
		case "超期未检":
			// 超期未检
			for ( var i in value) {
				info.push([ value[i].deviceName,
						getLocalTime(value[i].planFinishDate.time),
						getLocalTime(value[i].planStartDate.time),
						value[i].responsibleDepartment ]);
			}
			var columns = [ "设备名称", "计划完成日期", "计划开始日期", "责任单位" ];
			initTb(columns, info);
			break;
		case "断路器动作异常":
			// 断路器隐患
			for ( var i in value) {
				info.push([ value[i].breakerName,value[i].faultTime,
				           (Number(value[i].distance0MomentsTime)/1000).toFixed(1), (Number(value[i].xhTimeInterval)/1000).toFixed(1),
				           (Number(value[i].cross0Time)/1000).toFixed(1),value[i].phase,
				           "<button class='btn btn-primary' onclick='risk.openReport(\""+value[i].lineId+"\",\""+value[i].faultTime+"\",\""+value[i].lineName+"\")'><i class='fa fa-search'></i></button>" ]);
			}
			var columns = [ "开关名称","故障时间", "动作时间(ms)","熄弧时间(ms)","过零点时间(ms)", "相别", ""];
			initTb(columns, info);
			break;
		case "CT饱和":
			// CT饱和  
			for ( var i in value) {
				info.push([ value[i].lineName,value[i].faultTime,value[i].phase,
				            Math.abs(value[i].maxCurrent).toFixed(2), 
				            value[i].seventhPowerHarmonicProportion==""?"":Number(value[i].seventhPowerHarmonicProportion).toFixed(2),
				            value[i].areaProportion,
				            "<button class='btn btn-primary' onclick='risk.openReport(\""+value[i].lineId+"\",\""+value[i].faultTime+"\",\""+value[i].lineName+"\")'><i class='fa fa-search'></i></button>" ]);
			}
			var columns = [ "线路","故障时间", "相别", "最大电流","谐波比","面积比",""];
			initTb(columns, info);
			break;
		case "通信中断":
			// 通信中断
		/*	for ( var i in value) {
				info.push([ getLocalTime(value[i].eventStart.time),value[i].alarmMsg,
						value[i].durationTime,value[i].revertTime==null?"未复归":getLocalTime(value[i].revertTime.time),value[i].voltage
						]);
			}*/
			for ( var i in value) {
				info.push([ value[i].protectName,value[i].lineName,
				            value[i].continueMs,value[i].voltage
				            		]);
			}
			var columns = ["保护名称", "线路名称", "持续时间(ms)","电压等级"];
			initTb(columns, info);
			break;
		case "保护装置异常":
			// 保护装置异常
			for ( var i in value) {
				info.push([ value[i].protectName,value[i].continueMs,value[i].voltage]);
			}
			var columns = [ "保护名称","持续时间(ms)","电压等级"];
			initTb(columns, info);
			break;
		case "保护响应异常":
			// 保护响应异常
			for ( var i in value) {
				info.push([ value[i].protectionName,
						value[i].faultTime,Number(value[i].distance0MomentsTime)/1000,
						value[i].phase,value[i].manufacturer,
						 "<button class='btn btn-primary' onclick='risk.openReport(\""+value[i].lineId+"\",\""+value[i].faultTime+"\",\""+value[i].lineName+"\")'><i class='fa fa-search'></i></button>" ]);
			}
			var columns = [ "保护名称", "故障时间", "动作时间(ms)","故障相别","厂家","" ];
			initTb(columns, info);
			break;
		}
	}
	function initTb(columns, info) {
		var opt = MyTable.getDefaultOptions();
		opt.searching=true;
		opt.paging=true;
		opt.lengthChange=true;
		tb = new MyTable('detailTb', columns, opt);
		tb.setDataSet(info);
		tb.show();
		if(evalType.indexOf("断路器")>-1){
			//断路器动作异常的要标出是动作时间异常还是熄弧时间异常还是过零点异常
			tb.getTable().cells().every(function() {
				var data = this.data();
				if ((Number(data) >=Number(breakExpParam["act"])/1000 && this[0][0].column ==2)
						||(Number(data) >Number(breakExpParam["xh"])/1000 && this[0][0].column ==3)
						||(Number(data) >Number(breakExpParam["cross0"])/1000 && this[0][0].column == 4)) {
					$(this.node()).css("color","red");
				}
			});
		}
	}
	//链接到故障报告(lineId,faultTime,lineName)
	this.openReport=function(lineId,faultTime,lineName){
		if(lineId!=""&&faultTime!=""){
			openFaultReportPage(lineId,faultTime,lineName);
		}
	}
	
	
	//下面是treemap和bar
	
	// 确定等级颜色（treeMap）
	function getTreeMapGrade() {
		for (var i = 0; i < data.length; i++) {
			var name = data[i].name;
			var s = map.get(name);
			var deviceNum = map.get(name).length;// 相应的风险设备数目
			data[i].value.push(deviceNum);
			// 根据数目获取等级
			for (var j = 0; j < grade.length; j++) {
				if (deviceNum <= grade[j]) {
					data[i].itemStyle = {
						normal : {
							color : color[j]
						}
					};
					break;
				} else if (deviceNum > grade[grade.length - 1]) {
					// 最高等级取color最后一个元素
					data[i].itemStyle = {
						normal : {
							color : color[color.length - 1]
						}
					};
					break;
				}
			}
		}

	}

	// 确定等级颜色（柱状图）
	var colorList = [];// 根据个数确定每个柱子的颜色
	function getBarGrade() {
		for (var i = 0; i < data.length; i++) {
			var name = data[i].name;
			var s = map.get(name);
			var deviceNum = map.get(name).length;// 相应的风险设备数目
			// 根据数目获取等级
			for (var j = 0; j < grade.length; j++) {
				if (deviceNum <= grade[j]) {
					colorList.push(color[j]);
					break;
				} else if (deviceNum > grade[grade.length - 1]) {
					// 最高等级取color最后一个元素
					colorList.push(color[color.length - 1]);
					break;
				}
			}
		}
	}
	function initBarChart() {
		barChart.setxAxis(type);
		barChart.setyAxis(yData);
		// barChart.setyAxisName("个数");
		var option = barChart.getOption();
		option.toolbox.show = false;
		option.grid.top = 25;
		option.grid.bottom = 20;
		option.series[0].itemStyle.normal.color = function(params) {
			return colorList[params.dataIndex];
		}
		barChart.show();
	}
	function initTreeMapChart() {
		// 以下是矩形图，颜色代表等级，面积代表权重
		var option = treeMapChart.getOption();
		option.tooltip.formatter = function(param) {
			return param.name + ":" + param.value[1];
		}
		option.series[0].nodeClick = false;
		option.series[0].breadcrumb.show = false;
		option.series[0].label.normal = {
			formatter : function(param) {
				var value = param.value;
				var name = param.name;
				var str = name + "(" + value[1] + ")";
				return str;
			},
			textStyle : {
				fontSize : 18
			}
		};
		treeMapChart.setWidthAndHeight('100%', '95%').setLeafDepth(1);
		treeMapChart.setData(data);
		treeMapChart.show();
	}
	//设置chart点击事件
	this.setPrimeChartClicker=function(){
		barChart.getChart().on("click", function(param) {
			$(".box-header").show();
			var name = param.name;
			if (tb) {
				tb.getTable().destroy();
				$("#detailTb").empty();
			}
			$(".chartDiv").hide();
			$(".detailDiv").show();
			getPrimeData(name);
		});
		treeMapChart.getChart().on("click", function(param) {
			$(".box-header").show();
			var name = param.name;
			if (tb) {
				tb.getTable().destroy();
				$("#detailTb").empty();
			}
			$(".chartDiv").hide();
			$(".detailDiv").show();
			getPrimeData(name);
		});
	};
	this.setSecondChartClicker=function(){
		barChart.getChart().on("click", function(param) {
			$(".box-header").show();
			var name = param.name;
			if (tb) {
				tb.getTable().destroy();
				$("#detailTb").empty();
			}
			$(".chartDiv").hide();
			$(".detailDiv").show();
			getSecondData(name);
		});
		treeMapChart.getChart().on("click", function(param) {
			$(".box-header").show();
			var name = param.name;
			if (tb) {
				tb.getTable().destroy();
				$("#detailTb").empty();
			}
			$(".chartDiv").hide();
			$(".detailDiv").show();
			getSecondData(name);
		});
	};
}
